<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item label="教学点名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入名称关键字"
              clearable
              size="small"
              style="width: 160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="上传时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb10" style="float:right">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">
              <span>新增</span>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="courseList"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChang"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" sortable="custom" width="75" type="index" />
          <el-table-column label="教学点名称" prop="name" :show-overflow-tooltip="true" />
          <el-table-column label="所在地区" prop="province_text" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.City ? scope.row.City.name : "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" prop="dept_id_text">
            <template slot-scope="scope">
              <span>{{ scope.row.Department ? scope.row.Department.deptName : "-" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上传人" prop="creator" />
          <el-table-column label="创建时间" sortable="custom" prop="createdAt" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                :disabled="!multiple && single"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改对话框 -->
        <el-drawer ref="drawer" :title="title" :visible.sync="open" direction="rtl" custom-class="demo-drawer">
          <div class="demo-drawer__content">
            <el-form ref="form" :model="form" :rules="rules" label-width="110px">
              <el-form-item label="教学点名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="教学点地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="所属省份" prop="province_id">
                <el-select v-model="form.province_id" placeholder="请选择地址" style="width: 100%" @change="location1Change">
                  <el-option v-for="item in location1" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属城市" prop="city_id">
                <el-select
                  v-model="form.city_id"
                  filterable
                  placeholder="请选择地址"
                  style="width: 100%"
                  @change="location2Change"
                >
                  <el-option v-for="item in location2" :key="item.d" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属片区" prop="county_id">
                <el-select v-model="form.county_id" filterable placeholder="请选择地址" style="width: 100%">
                  <el-option v-for="item in location3" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="所属部门" prop="department_id">
                <treeselect
                  v-model="form.department_id"
                  :options="deptOptions"
                  placeholder="请选择归属部门"
                  @input="handleChange"
                />
              </el-form-item>
              <el-form-item label="教学点负责人" prop="controller_id">
                <el-select v-model="form.controller_id" style="width: 100%" multiple placeholder="请选择">
                  <el-option
                    v-for="item in userArray"
                    :key="item.user_id"
                    :label="item.nick_name"
                    :value="item.user_id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="招生老师" prop="enrollment_id">
                <el-select v-model="form.enrollment_id" style="width: 100%" multiple placeholder="请选择">
                  <el-option
                    v-for="item in userArray"
                    :key="item.user_id"
                    :label="item.nick_name"
                    :value="item.user_id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-drawer>
      </el-card>
    </template>
  </BasicLayout>
</template>

<script>
import {
  getSchoolList,
  addSchool,
  deletePoint,
  getSchoolDetails,
  editSchool
} from '@/api/admin/sys-academy'
import { getRegion, getUserList } from '@/api/admin/sys-course'
import { treeselect } from '@/api/admin/sys-dept'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { flatten } from '@/utils/index'

export default {
  name: 'SysAcademy',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      chooseIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      courseList: [],
      // 排序字段
      order: 'createdAtOrder',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        created_at: undefined,
        name: undefined
      },
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      location1: null,
      location2: null,
      location3: null,
      selectload: false,
      deptOptions: [],
      userArray: []
    }
  },
  watch: {
    open(newVal) {
      if (newVal === true && this.form.province_id) {
        getRegion({ parent_id: this.form.province_id }).then(res => {
          this.location2 = res.data
        })
        if (this.form.city_id) {
          getRegion({ parent_id: this.form.city_id }).then(res => {
            this.location3 = res.data
          })
        }
      }
    }
  },
  created() {
    this.getList()
    this.host = process.env.VUE_APP_BASE_API
    this.getLocation()
    getUserList({
      status: '2',
      post_id: [49, 50, 51, 52]
    }).then(res => {
      this.userArray = res?.data
    })
    treeselect().then(response => {
      this.deptOptions = this.IterationDelateMenuChildren(response.data)
    })
  },
  methods: {
    IterationDelateMenuChildren(arr) {
      if (arr.length) {
        for (const i in arr) {
          if (arr[i].children.length) {
            this.IterationDelateMenuChildren(arr[i].children)
          } else {
            delete arr[i].children
          }
        }
      }
      return arr
    },
    /** 获取所属大区 */
    getLocation() {
      getRegion({ parent_id: 1 }).then(res => {
        this.location1 = res?.data
      })
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true
      getSchoolList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.courseList = response.data.list
          this.total = response.data.count
          this.loading = false
        }
      )
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseIds = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.chooseIds
      this.$confirm('是否确认删除', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return deletePoint({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() { })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加教学点'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getSchoolDetails(row?.id).then(res => {
        const { data } = res
        const controllerId = data?.Controllers?.map(item => {
          return item?.userId
        })
        const enrollmentId = data?.Enrollments?.map(item => {
          return item?.userId
        })
        const prmars = {
          name: data?.name,
          city_id: data?.city_id,
          county_id: data?.county_id,
          department_id: data?.department_id,
          id: data?.id,
          province_id: data?.province_id,
          controller_id: controllerId,
          enrollment_id: enrollmentId,
          address: data?.address
        }
        this.form = prmars
        this.open = true
        this.title = '修改教学点'
      })
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id) {
            editSchool(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess(res.msg)
                this.open = false
                this.getList()
              } else {
                this.msgError(res.msg)
              }
            })
            return
          }
          addSchool(this.form).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.open = false
              this.getList()
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    location1Change(value) {
      this.form = {
        ...this.form,
        city_id: null,
        county_id: null
      }
      getRegion({ parent_id: value }).then(res => {
        this.location2 = res.data
      })
    },
    location2Change(value) {
      this.form = {
        ...this.form,
        county_id: null
      }
      getRegion({ parent_id: value }).then(res => {
        this.location3 = res.data
      })
    },

    handleChange(value) {
      const filtrate = flatten(this.deptOptions)?.filter(
        item => item?.id === value
      )
      this.form = {
        ...this.form,
        dept_id_text: filtrate[0]?.label
      }
    },

    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        this.selectload = false
      } else {
        this.location1 = []
      }
    }
  }
}
</script>
